﻿using System;
using System.Activities;
using System.Linq;
using Reactor.Environment;
using Reactor.Workflow.Activities;

namespace Reactor.ServiceGrid.Workflows.Activities
{
    public class ObtainServiceInstanceIdentifier : ReactorCodeActivityBase<Guid>
    {
        [RequiredArgument]
        public InArgument<string> OwningCoreName { get; set; }

        [RequiredArgument]
        public InArgument<ServiceIdentifier> ServiceIdentifier { get; set; }

        #region Overrides of CodeActivity

        /// <summary>
        /// When implemented in a derived class, performs the execution of the activity.
        /// </summary>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override Guid Execute(CodeActivityContext context)
        {
            var owningCoreName = context.GetValue(OwningCoreName);
            var serviceIdentifer = context.GetValue(ServiceIdentifier);
            var coreDataProvider = Context.GridContext.CoreDataProvider;

            if (Log.IsDebugEnabled) Log.DebugFormat("Attempting to obtain instance identifier for service: {0} version: {1} assigned to Core: {2}.", serviceIdentifer.Name, serviceIdentifer.Version, owningCoreName);

            var serviceInstanceIdentifier =
                (from s in coreDataProvider.GetAllServiceInstancesAssignedToCore(new ServiceIdentifier(owningCoreName, new Version("1.0.0.0")))
                 where s.Identifier.Name == serviceIdentifer.Name && s.Identifier.Version == serviceIdentifer.Version
                 select s.InstanceIdentifier).SingleOrDefault();

            if(serviceInstanceIdentifier == Guid.Empty)
                throw new ApplicationException(string.Format("Unable to obtain instance identifier for service: {0} version: {1} assigned to Core: {2}.", serviceIdentifer.Name, serviceIdentifer.Version, owningCoreName));

            if (Log.IsDebugEnabled) Log.DebugFormat("Service instance identifier obtained: {0}", serviceInstanceIdentifier);

            return serviceInstanceIdentifier;
        }

        #endregion
    }
}
